package com.yq.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yq.backend.dto.CardProductsDto;
import com.yq.backend.mapper.CardProductMapper;
import com.yq.backend.pojo.CardProduct;
import com.yq.backend.pojo.Result;
import com.yq.backend.service.CardProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @descriptions: 奖品业务实现类
 * @author: yunqiang
 * @date: 2022/5/3 20:11
 */
@Service
@Slf4j
public class CardProductServiceImpl implements CardProductService {

    @Autowired
    private CardProductMapper cardProductMapper;

    /**
     * 添加奖品
     * @param cardProduct
     * @return
     */
    @Override
    public Result addCardProduct(CardProduct cardProduct) {
        List<CardProduct> cardProducts = cardProductMapper.
                selectList(new QueryWrapper<CardProduct>().lambda().eq(CardProduct::getName, cardProduct.getName()));
        if (cardProducts.size() > 0) {
            return Result.error(505, "奖品名称已存在！");
        }
        this.cardProductMapper.insert(cardProduct);
        return Result.success();
    }

    /**
     * 修改奖品
     * @param cardProduct
     * @return
     */
    @Override
    public Result upCardProduct(CardProduct cardProduct) {
        this.cardProductMapper.updateById(cardProduct);
        return Result.success();
    }

    /**
     * 删除奖品
     * @param id
     * @return
     */
    @Override
    public Result delCardProduct(Integer id) {
       this.cardProductMapper.deleteById(id);
        return Result.success();
    }

    /**
     * 根据id查询奖品
     * @param id
     * @return
     */
    @Override
    public Result cardProduct(Integer id) {
        CardProduct cardProduct = this.cardProductMapper.selectById(id);
        return cardProduct==null?Result.noResult():Result.success(cardProduct);
    }

    /**
     * 奖品列表
     * @param cardProductsDto
     * @return
     */
    @Override
    public Result getCardProducts(CardProductsDto cardProductsDto) {
        int pageNow = cardProductsDto.getPageNow();
        int pageSize = cardProductsDto.getPageSize();
        if (pageNow > 0){
            pageNow  =(pageNow - 1)*pageSize;
        }else{
            pageNow = 0;
        }
        long total = cardProductMapper.getCardProductCount(cardProductsDto);
        List<CardProduct> cardProducts = cardProductMapper.getCardProducts(cardProductsDto,pageNow,pageSize);
        if(CollectionUtils.isEmpty(cardProducts)){
            return Result.noResult();
        }
        return Result.success(total,cardProducts);
    }
}
